# __init__.py 为初始入口文件,工程代码的入口文件.

# 导入动作库常用函数
from ascript.android.action import click,slide,Touch,gesture
# 导入控件检索相关
from ascript.android.node import Selector
# 导入系统相关
from ascript.android import system
# 环境设备相关
from ascript.android.system import R,Device
from ascript.android.action import swipe
from ascript.android.ui import FloatWindow

from time import sleep,time
import re

Dialog.toast("3秒后将隐藏悬浮按钮",dur=1000,x=0,y=0.28,bg_color="#00FFFFFF")
sleep(1)
Dialog.toast("Running...",dur=3000,x=0,y=0.28,bg_color="#00FFFFFF")
#print("3秒后将隐藏悬浮按钮")
sleep(3)
FloatWindow.hide()
# 点击某个地方
# click(100,100)
devicebrand = Device.brand()
print(f"devicebrand = {devicebrand}")




def main():
    last_record = None
    #oriT = int(time())
    ori_pass_nodes = [] #pass_nodes[0][0] 表示经过强行停止等相关界面 pass_nodes[1][0] 表示 经过快手等相关界面
    #wrong_step_count = 0 #用于统计仅在强行停止中循环的次数

    while True:
        #pass_nodes = [[False,0],[False,0]] #pass_nodes[0] 表示经过强行停止等相关界面 pass_nodes[1] 表示 经过快手等相关界面
        pass_node = []
        #temp_wrong_step_count = wrong_step_count
        isalive = False
        node = Selector().desc("(已|未)点赞，点赞").visible(True).find()
        if node:
            pass_node = ["kuai",int(time())]
            #print("find kuai 0")
            current_record = node.desc
            if re.findall("已点赞",current_record):
                sleep(3)
                continue
            if current_record and current_record != last_record:
                print(f"node.desc = {current_record}")
                last_record = current_record
                if devicebrand == "XIAOMI":
                    swipecore()
        else:
            if Selector().id("com.smile.gifmaker:id/toast_text").text(r".*[\s]?操作太快了，请稍微休息一下").find() or \
                Selector().text("没有获取到订单").find() or Selector().desc("没有获取到订单").find(): # 获取订单这个toast节点获取不到
                isalive = True
                #print("find isalive")
            elif Selector().packageName("com.smile.gifmaker").find():
                pass_node = ["kuai",int(time())]
                #print("find kuai 1")
            elif Selector().text("取消").visible(True).find() and Selector().text('要强行停止吗.*|.*强行停止.*应用.*').find():
                #print("已找到 强行停止/确定，取消/卸载")
                pass_node = ["stop",int(time())]
            
            elif Selector().text("卸载").visible(True).find() and Selector().text("快手").visible(True).find():
                #print("已找到 卸载-快手")
                pass_node = ["stop",int(time())]
                



        floatCtrl()
        sleep(1)
            #else:
                #sleep(1)
                #continue
        if isalive:
            ori_pass_nodes = []
        else:
            temp_different = False
            
            ori_pass_nodes = ori_pass_nodes[-2:]
            #print(f"ori_pass_nodes = {ori_pass_nodes}")
            #index = len(ori_pass_nodes) - 1
#            for pass_nodes in reversed(ori_pass_nodes):
#
#                if pass_node and pass_node[0] != pass_nodes[0]: # and index == 0
#                    temp_different = True
#                elif pass_node and pass_node[0] == pass_nodes[0]:
#                    ori_pass_nodes.remove(pass_nodes)
#                    temp_different = True
#                    break
                #index -= 1
            #length = len(ori_pass_nodes)
            #print(f"length = {length}")
            if pass_node:
                if len(ori_pass_nodes) == 0:
                    ori_pass_nodes.append(pass_node)
                elif pass_node[0] != ori_pass_nodes[-1][0]:
                    #temp_different = True
                    #print("temp_different is false")
                    ori_pass_nodes.append(pass_node)
                else:
                    #print("temp_different is true")
                    #ori_pass_nodes[-1] = pass_node
                    sub = pass_node[1] - ori_pass_nodes[-1][1]
                    #print(f"sub = {sub}")
                    if pass_node[0] == "stop" and sub >= 3 * 60:
                        print("疑似在快手界面循环，距离上次相同节点无变化已经超过3分钟")
                        点击重新开始()
                        ori_pass_nodes = []
                    elif pass_node[0] == "kuai" and sub >= 5 * 60:
                        print("疑似在快手界面循环，距离上次相同节点无变化已经超过5分钟")
                        点击重新开始()
                        ori_pass_nodes = []
#            if temp_different:
#                print("temp_different is true")
#                #ori_pass_nodes = []
#                ori_pass_nodes.append(pass_node)
#            else:
#                print("temp_different is false")
#                if ori_pass_nodes and pass_node and pass_node[0][1] - ori_pass_nodes[-1][1] > 1*60:
#                print("距离上次相同节点无变化已经超过1分钟")
            




def movebyslide(x,y,plus = 150 ):
    sleep(0.5)
    slide(x, y, x, y - plus, 1000)
    sleep(0.8)
    slide(x, y - plus, x, y, 1000)

def movebytouch(x = 927,y = 108):
    print("slide at movebytouch()")
    sleep(0.5)
    Touch.down(x, y, 300)
    sleep(0.2) 
    Touch.move(x, y + 150,1500)
    sleep(0.3)
    Touch.up(x, y + 150,300)

def slidenew():
    #Selector().id("com.smile.gifmaker:id/camera_btn_layout").find() #摄像头
    search = Selector().id("com.smile.gifmaker:id/nasa_featured_default_search_view").visible(True).find() or Selector().id("com.smile.gifmaker:id/search_btn").desc("查找").find() # 搜索按钮
    if search:
        x = search.rect.centerX()
        y = search.rect.centerY()
        if x <= 800 and y >= 300:
            return []
        return [x,y]
    return []

def swipecore(msg = "准备查找展开按钮"):
    print(msg)
    node = Selector().text("展开").find()
    if node:
        print(f"已找到--展开，即将滑动")
        point = slidenew()
        if point:
            [x,y] = point
            print(f"已找到--搜索按钮，x, y 坐标 = {x}, {y}，即将滑动")
            movebytouch(x=x,y=y)
        else:
            movebytouch()


def floatCtrl():
    while True:
        nodes = Selector().packageName("com.aojoy.airscript").find_all() or []
        if len(nodes) > 0:
            if not Selector().desc("AoJoyLog").find():
                FloatWindow.show()
            elif len(nodes) > 1:
                pass
            elif len(nodes) == 1 and nodes[0].desc == "AoJoyLog":
                FloatWindow.hide()
                break
        else:
            break
        sleep(5)

def 点击重新开始():
    ks = True
    tz = True
    zk = True
    startT = time() 
    while True:
        if Selector().text("卸载").visible(True).find() and Selector().text("快手").visible(True).find():
            recents()
            sleep(1000)

        if ks and Selector().text("开始运行").type("TextView").click().find():
            tz = False
        elif tz and Selector().text("停止运行").type("TextView").click().find():
            sleep(0.5)
            zk = False
        else:
            node = Selector().text("展开").find()
            if zk and node:
                print(f"已找到--展开，即将滑动")
                x = node.rect.centerX()
                y = node.rect.centerY()
                click(x,y)
            sleep(0.5)
            
        if not zk and not tz and ks:
            if not  Selector().text("开始运行").type("TextView").find():
                return
        if time() - startT > 10:
            return
main()
